/*
 * nalu_extractor.c
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include "nalu.h"

/* Fill all structures in Nalu_info */
/* nalu_info->layer to get the NALU layer */
int fill_nalu_struct_with_rtp_payload(char *rtp_payload, Nalu_info *nalu_info){

	/* Filling structures */
	// nalu_info->nalu.nalu_hdr = (Nalu_Hdr *)rtp_payload;

	nalu_info->nalu.nalu_hdr.forbidden_zero_bit 		= (unsigned int) ((rtp_payload[0] >> 7) & 0x01);
	nalu_info->nalu.nalu_hdr.nri 						= (unsigned int) ((rtp_payload[0] >> 5) & 0x02);
	nalu_info->nalu.nalu_hdr.type					= (unsigned int) ((rtp_payload[0] >> 0) & 0x1f);

	// nalu_info->nalu.nalu_svc_hdr = (Nalu_SvcExtensionHdr *)(rtp_payload+sizeof(Nalu_Hdr));

	nalu_info->nalu.nalu_svc_hdr.svc_extension_flag	= (unsigned int) ((rtp_payload[1] >> 7) & 0x01);
	nalu_info->nalu.nalu_svc_hdr.idr_flag				= (unsigned int) ((rtp_payload[1] >> 6) & 0x01);
	nalu_info->nalu.nalu_svc_hdr.priority_id			= (unsigned int) ((rtp_payload[1] >> 0) & 0x3f);
	nalu_info->nalu.nalu_svc_hdr.no_inter_layer_pred_flag = (unsigned int) ((rtp_payload[2] >> 7) & 0x01);
	nalu_info->nalu.nalu_svc_hdr.dependency_id		= (unsigned int) ((rtp_payload[2] >> 4) & 0x07);
	nalu_info->nalu.nalu_svc_hdr.quality_id			= (unsigned int) ((rtp_payload[2] >> 0) & 0x0f);
	nalu_info->nalu.nalu_svc_hdr.temporal_id			= (unsigned int) ((rtp_payload[3] >> 5) & 0x07);
	nalu_info->nalu.nalu_svc_hdr.use_ref_base_pic_flag= (unsigned int) ((rtp_payload[3] >> 4) & 0x01);
	nalu_info->nalu.nalu_svc_hdr.discardable_flag		= (unsigned int) ((rtp_payload[3] >> 3) & 0x01);
	nalu_info->nalu.nalu_svc_hdr.output_flag			= (unsigned int) ((rtp_payload[3] >> 2) & 0x01);
	nalu_info->nalu.nalu_svc_hdr.reserved_three_2bits	= (unsigned int) ((rtp_payload[3] >> 0) & 0x03);

	nalu_info->nalu.payload = (char *)(rtp_payload+sizeof(Nalu_Hdr)+sizeof(Nalu_SvcExtensionHdr));

	/* The layer is normaly a matrix of three dimensions, 											*/
	/* but with DqId we join dependency_id and quality_id in only one parameter. 					*/
	/* Thus, we just have a two dimensions matrix.													*/
	/* Check at http://hal.archives-ouvertes.fr/docs/00/56/00/27/PDF/OpenSVCDecoder.pdf	. Figure 1	*/

	/* Calculate Nalu DqId - cf. draft-ietf-avt-rtp-svc */
	nalu_info->layer.DqId = ( nalu_info->nalu.nalu_svc_hdr.dependency_id << 4 ) + nalu_info->nalu.nalu_svc_hdr.quality_id;
	nalu_info->layer.temporal_id = nalu_info->nalu.nalu_svc_hdr.temporal_id;
	/* Layer is now in nalu_info->layer. */

	return(0);
}
